Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,

Given [3,2,1,5,6,4] and k = 2, return 5.

Note:

You may assume k is always valid, 1 ≤ k ≤ array’s length.

Solution:

  1. public class Solution {
  2. public int findKthLargest(int[] a, int k) {
  3. int n = a.length;
  4. int p = quickSelect(a, 0, n - 1, n - k + 1);
  5. return a[p];
  6. }
  7. // return the index of the kth smallest number
  8. int quickSelect(int[] a, int lo, int hi, int k) {
  9. // use quick sort's idea
  10. // put nums that are <= pivot to the left
  11. // put nums that are > pivot to the right
  12. int i = lo, j = hi, pivot = a[hi];
  13. while (i < j) {
  14. if (a[i++] > pivot)
  15. swap(a, --i, --j);
  16. }
  17. swap(a, i, hi);
  18. // count the nums that are <= pivot from lo
  19. int m = i - lo + 1;
  20. // pivot is the one!
  21. if (m == k) return i;
  22. // pivot is too big, so it must be on the left
  23. else if (m > k) return quickSelect(a, lo, i - 1, k);
  24. // pivot is too small, so it must be on the right
  25. else return quickSelect(a, i + 1, hi, k - m);
  26. }
  27. void swap(int[] a, int i, int j) {
  28. int tmp = a[i];
  29. a[i] = a[j];
  30. a[j] = tmp;
  31. }
  32. }